//
//  NetworkService+TianHai.m
//  ZhuShou
//
//  Created by Dejun Liu on 15/9/24.
//  Copyright (c) 2015年 jw. All rights reserved.
//

#import "NetworkService+TianHai.h"
#import "NSArray+KBJSONSerializing.h"
#import "NSDictionary+KBJSONSerializing.h"
#import "NSString+KBJSONSerializing.h"
#import <MJExtension/MJExtension.h>

#define URSSring @"http://openapi.tianhi.com/api.svc/api"
#define NSUsername @"test"
#define NSPassword @"test"

@implementation NetworkService (TianHai)

- (void)th_postWithParams:(NSDictionary *)params action:(NSString *)action completion:(THComplation)aCompletion
{
    NSString *xml = [self buildXMLWithParams:params action:action];
    DLog(@"post======:%@",xml);
    [self postDataString:xml urlString:URSSring jsonResponse:^(id responseData, NSError *error) {
        NSDictionary *dic = responseData;
        DLog(@"data======:%@",[dic JSONString]);
        aCompletion(responseData,error);
    }];
}

- (NSString *)buildXMLWithParams:(NSDictionary *)paramsDic action:(NSString *)action
{
    NSMutableString *params = [NSMutableString string];
    [params appendFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"];
    [params appendFormat:@"<request>"];
    [params appendFormat:@"<public>"];
    [params appendFormat:@"<functioncode>%@</functioncode>",action];
    [params appendFormat:@"<requestid>%.0f</requestid>",[[NSDate date] timeIntervalSince1970]];
    [params appendFormat:@"<ver>1.0</ver>"];
    [params appendFormat:@"<datatype>1</datatype>"];
    [params appendFormat:@"<username>%@</username>",NSUsername];
    [params appendFormat:@"<password>%@</password>",NSPassword];
    NSString *dateString = [NSDate stringFromDate:[NSDate date] withFormat:@"yyyyMMddHHmmss"];
    [params appendFormat:@"<timestamp>%@</timestamp>",dateString];
    [params appendFormat:@"<unitid>ad</unitid>"];
    [params appendFormat:@"<source>201</source>"];
    [params appendFormat:@"</public>"];
    [params appendFormat:@"<reqdata>"];
    //参数
    [paramsDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [params appendFormat:@"<%@>",key];
        [params appendFormat:@"%@",obj];
        [params appendFormat:@"</%@>",key];
    }];
    
    [params appendFormat:@"</reqdata>"];
    [params appendFormat:@"</request>"];
    return params;
}

@end
